<!-- 头部搜索 -->
<template>
<div class="topsearch">
    <div>
        <el-input placeholder="输入关键字" v-model="searchHouseKeyword" class="input-with-select" style="background: #fff;">
            <el-select v-model="selectTool" slot="prepend" placeholder="请选择" style="width: 105px;">
                <el-option v-for="(item,index) in tools" :key="index" :label="item.title" :value="item.id"></el-option>
            </el-select>
            <el-button slot="append" @click="_searchHouse()"><span style="color:#409eff;">搜索</span></el-button>
        </el-input>
    </div>
    <!-- 显示查询结果 -->
    <div id="resultTable" v-if="showResult" style="width:100vw;position:fixed;background:#fff;left: 0px;" :style="isUp? {height: vheight+'vh', top:'0' }:{height: vheight+'vh', bottom:'0' }">
        <div class="top-result" @click="_setheight()">
            <!-- <img v-if="isUp" :src="imgpath+'down.png'" style="width:30px;">
            <img v-else :src="imgpath+'upward.png'" style="width:30px;"> -->
            <img v-if="isUp" :src="imgpath1" style="width:30px;">
            <img v-else :src="imgpath2" style="width:30px;">
        </div>
        <div class="content-result" style="height: calc(30vh - 30px);overflow-y: auto; background: #FAFAFA;" :style="isUp? {height: 'calc('+vheight+'vh - 30px)'}:{height: 'calc('+vheight+'vh - 30px)'}">
            <div v-infinite-scroll="_load">
                <div class="search-result" style="height: 90px; cursor: pointer;border: 1px solid rgb(228, 231, 237); margin: 7px; border-radius: 5px; background: #fff; width: calc(100% - 14px);" v-for="(feature, findex) in houseSearchResult_Show" :key="findex" @click="_locateResultInit(feature, 'house')">
                    <table>
                        <tr>
                            <td style="text-align: left;width: 70px">
                                {{ feature.displayFieldName != undefined &&feature.displayFieldName != null && feature.displayFieldName[0] != undefined && feature.displayFieldName[0] != ""? feature.attributes[feature.displayFieldName[0] ] : ""}}
                            </td>
                            <td style="">
                                {{ feature.displayFieldName != undefined && feature.displayFieldName != null && feature.displayFieldName[1] != undefined && feature.displayFieldName[1] != "" ? feature.attributes[ feature.displayFieldName[1] ].length > 20 ? feature.attributes[ feature.displayFieldName[1] ].substring(0, 20) : feature.attributes[ feature.displayFieldName[1] ] : "" }}
                            </td>
                        </tr>
                        <tr>
                            <td style="width: calc(100% - 70px) !important;color:#1A1A1A;font-size:20px;" colspan="2">
                                {{ feature[resultCol.objname1] != ""? feature[resultCol.objname1]: "无" }}
                            </td>
                        </tr>
                        <tr>
                            <td style="width: 70px;color:#848484;font-size:14px;">自建房排查编号：</td>
                            <td style="width: calc(100% - 70px) !important;color:#848484;font-size:14px;">
                                {{ feature[locationObjName] != ""? feature[locationObjName]: "无" }}
                            </td>
                        </tr>
                        <tr>
                            <td style="width: calc(100% - 70px) !important;" colspan="2">
                                <div style="height:auto;white-space: normal;color:#848484;font-size:14px;">
                                    {{ feature[resultCol.objname3] != ""? feature[resultCol.objname3]: "无" }}
                                </div>
                            </td>
                        </tr>
                    </table>
                </div>
            </div>
            <!-- 下拉加载时候加loading旋转动效 -->
            <div v-if="loading" style="margin-top:10px;" class="loading">
                <span></span>
            </div>
            <!-- 加载完成，提示语句 -->
            <div v-if="noMore" style="margin:10 auto; text-align: center; font-size:18px;font-weight: 550; color:#000000">--------</div>
        </div>
    </div>
</div>
</template>

<script>
import * as api from '../../../utils/api_gis'
import * as esriLoader from "esri-loader";
import MapManager from "../../../core/mapManager";
export default {
    data() {
        return {
            // imgpath1: window.location.origin + window.location.pathname + "static/img/topsearch/down.png",
            // imgpath2: window.location.origin + window.location.pathname + "static/img/topsearch/upward.png",
            imgpath1: "../../../../static/imgs/topsearch/down.png",
            imgpath2: "../../../../static/imgs/topsearch/upward.png",
            cityCode: "",
            searchHouseKeyword: '',
            showResult: false,
            isUp: false,
            vheight: 30, //返回结果table的默认高度

            //搜索
            tools: window.g.Project.leftTools,
            selectTool: "农房审批",

            //查询结果相关
            loading: false, //加载时的动画
            pageIndex: 1, //分页查询后端所需参数，【确认后端所需的参数名，有的接口不一样，根据实际情况而定】，
            pageNo: 1,
            pageSize: 10,
            houseSearchResult_Show: [],
            houseSearchResultGraphics: [],
            houseSearchResultCount: 0,

            resultCol: {
                objname1: "SQRXM",
                objname2: "FWBH",
                objname3: "JFDZ",
            },
            locationObjName: "FWBH",

        };
    },

    components: {},
    computed: {
        noMore() {
            //当起始页数大于总页数时停止加载
            // return this.pageIndex >= this.pageNo;
            return this.pageNo >= this.pageIndex;
        },
        disabled() {
            return this.loading || this.noMore;
        }
    },
    methods: {
        //查询房屋数据
        _searchHouse(){
            this.houseSearchResult_Show = []
            this.pageNo = 1
            this._searchHouseNew()
        },
        _searchHouseNew: async function () {
            const self = this
            debugger
            let type = 1
            switch (self.selectTool) {
                case "农房审批":
                    type = 1
                    self.resultCol.objname1 = "SQRXM"
                    self.resultCol.objname2 = "SQBH"
                    self.resultCol.objname3 = "JFDZ"
                    self.locationObjName = "FWBH"
                    break;
                case "农房建设":
                    type = 2
                    self.resultCol.objname1 = "HZXM"
                    self.resultCol.objname2 = "SQBH"
                    self.resultCol.objname3 = "JFDZ"
                    self.locationObjName = "FWBH"
                    break;
                case "存量农房":
                    type = 3
                    self.resultCol.objname1 = "cqr"
                    self.resultCol.objname2 = "yhfwbh"
                    self.resultCol.objname3 = "address"
                    self.locationObjName = "yhfwbh"
                    break;
                case "危房改造":
                    type = 4
                    self.resultCol.objname1 = "property_person"
                    self.resultCol.objname2 = "check_number"
                    self.resultCol.objname3 = "detail_address"
                    self.locationObjName = "check_number"
                    break;
            }
            self.$forceUpdate()
            let cityCode = self.cityCode
            if (cityCode.substring(0, 12) === "330000000000") { //省级
                cityCode = "33"
            } else if (cityCode.substring(4, 12) === "00000000") { //市级
                cityCode = cityCode.substring(0, 4)
            } else if (cityCode.substring(6, 12) === "000000") { //区县
                cityCode = cityCode.substring(0, 6)
            } else if (cityCode.substring(9, 12) === "000") { //乡镇
                cityCode = cityCode.substring(0, 9)
            } else {
                cityCode = "33"
            }
            let xm = self.searchHouseKeyword

            let param = `type=${type}&cityCode=${cityCode}&xm=${xm}&pageNo=${self.pageNo}&pageSize=${self.pageSize}`
            const res = await api.houseSearch(param);
            if (res.data.code == "200" && res.data.data.total > 0) {
                self.showResult = true
                res.data.data.list.forEach(element => {
                    self.houseSearchResult_Show.push(element)
                });
                if (res.data.data.total % self.pageSize != 0) {
                    self.pageIndex = (res.data.data.total / self.pageSize) + 1
                } else {
                    self.pageIndex = (res.data.data.total / self.pageSize)
                }
            } else {
                self.$message.info("查询" + "户主姓名或房屋编码为 " + self.searchHouseKeyword + " 的结果为空");
            }
        },
        //判断省市||区县
        _citycode1(str) {
            if (str.endsWith('0000000000')) {
                return "省"
            } else if (str.endsWith('00000000')) {
                return "市"
            } else if (str.endsWith('000000')) {
                return "县"
            } else if (str.endsWith('000')) {
                return "村镇"
            }
        },
        //定位初始化获取信息
        _locateResultInit: async function (feature) {
            const self = this
            
            let type = 1
            let url = ""
            switch (self.selectTool) {
                case "农房审批":
                    type = 1
                    url = window.g.MapConfiguration.lifeCircleLayers["农房审批"][0]["url"]
                    break;
                case "农房建设":
                    type = 2
                    url = window.g.MapConfiguration.lifeCircleLayers["农房建设"][0]["url"]
                    break;
                case "存量农房":
                    type = 3
                    url = window.g.MapConfiguration.lifeCircleLayers["存量农房"][0]["url"]
                    break;
                case "危房改造":
                    type = 4
                    url = window.g.MapConfiguration.lifeCircleLayers["危房改造"][0]["url"]
                    break;
            }

            if (feature[self.resultCol.objname2] == "") {
                self.$message.info("房屋编码为空，无法定位...")
                return;
            }

            let cityCode = self.cityCode
            if (cityCode.substring(0, 12) === "330000000000") { //省级
                cityCode = "33"
            } else if (cityCode.substring(4, 12) === "00000000") { //市级
                cityCode = cityCode.substring(0, 4)
            } else if (cityCode.substring(6, 12) === "000000") { //区县
                cityCode = cityCode.substring(0, 6)
            } else if (cityCode.substring(9, 12) === "000") { //乡镇
                cityCode = cityCode.substring(0, 9)
            } else {
                cityCode = "33"
            }
            
            if ( type == 4) { //没有坐标信息，需要查询一个接口获取
                let params = {
                    "pageNum": 1,
                    "pageSize": 20,
                    "cityCode": cityCode,
                    "yhfwbh": feature[self.resultCol.objname2], //"YH330825000074863",//
                }
                const res = await api.houseList(params);
                if (res.data.data.pageList && res.data.data.pageList.length > 0) {
                    self._locateResult(res.data.data.pageList[0], "geomP")
                } else {
                    self.$message.info("未查询到坐标信息...")
                }
            }else if(type == 3){
                self._locateResult(feature, "geom_p")
            } else { //有坐标信息，查询矢量图层
                let where = ` ${self.resultCol.objname2} = '${feature[self.resultCol.objname2]}'`
                const pro1 = self._returnFeatureFromWhere(url, where, null)
                Promise.all([pro1]).then((result) => {
                    if(result[0].features.length > 0){
                        const features = result[0].features
                        self._location(features[0]["attributes"], features[0]["geometry"])
                    }else{
                        self.$message.info("未查询到定位信息！")
                    }
                })

            }
        },
        //定位     
        _locateResult(attributes, fieldname) {
            const self = this

            if (!attributes[fieldname]) {
                self.$message.info("未获取到定位信息！")
                return
            }

            self.mapView.graphics.removeAll()
            let pgeometry = null

            let rings = attributes[fieldname].replace(/(MULTIPOLYGON)|(\(\(\()|(\)\)\))/g, "");
            rings = rings.replace(/ /g, ",");
            rings = JSON.parse("[" + rings + "]");
            let ringsList = [];
            for (let index = 0; index < rings.length; index += 2) {
                ringsList.push([rings[index], rings[index + 1]]);
            }
            pgeometry = new self.Polygon({
                rings: ringsList,
                spatialReference: self.mapView.spatialReference
            })
            self._location(attributes, pgeometry)
        },
        _location(attributes, pgeometry) {
            const self = this

            //打开详情框
            const fields = [{
                name: "ObjectID",
                alias: "ObjectID",
                type: "oid"
            }];
            for (let k in attributes) {
                fields.push({
                    name: k,
                    alias: k,
                    type: "string",
                });
            }
            let graphic = new self.Graphic({
                geometry: pgeometry,
                attributes: attributes,
                symbols: window.g.MapConfiguration.HighlightSymbol.polygon,
                popupTemplate: {
                    title: "",
                    content: [{
                        type: "fields",
                        fieldInfos: fields.filter((f) => {
                            return f.type !== "oid";
                        }).map((f) => {
                            return {
                                fieldName: f.name,
                                label: f.alias,
                            };
                        }),
                    }],
                    // actions: actions,
                    outFields: ["*"],
                }
            });
            let point = new self.Graphic({
                geometry: pgeometry.centroid,
                symbol: window.g.MapConfiguration.HighlightSymbol.point,
                spatialReference: self.mapView.spatialReference
            })
            self.mapView.graphics.addMany([graphic, point])
            self.mapView.goTo({
                target: point,
                zoom: window.g.MapConfiguration.FullViewInfo.zoom
            }, {
                easing: 'ease-out',
                duration: 100
            })
            self.mapView.popup.open({
                features: [graphic],
                featureMenuOpen: true,
                updateLocationEnabled: true,
            });
        },
        //获取图层范围内的数据
        _returnFeatureFromWhere(url, where, geo) {
            const self = this
            return new Promise((resolve, reject) => {
                const query = new self.Query();
                query.returnGeometry = true;
                query.outFields = ["*"];
                query.where = where
                query.geometry = geo ? geo : null;
                query.outSpatialReference = self.mapView.spatialReference
                const queryTask = new self.QueryTask(url);
                queryTask.execute(query)
                    .then(response => {
                        resolve(response)
                    })
            })
        },
        //设置返回结果所占高度
        _setheight() {
            const self = this
            self.isUp = !self.isUp
            if (self.isUp) {
                self.vheight = 100;
            } else {
                self.vheight = 30;
            }
            self.$forceUpdate();
        },
        //获取url地址中的某一个参数值
        _getUrlParam(paraName) {
            var url = document.location.toString();
            let Objurl = url.substring(url.lastIndexOf("?") + 1, url.length);
            if (Objurl.length > 1) {
                var arrPara = Objurl.split("&");
                var arr;

                for (var i = 0; i < arrPara.length; i++) {
                    arr = arrPara[i].split("=");

                    if (arr != null && arr[0] == paraName) {
                        return arr[1];
                    }
                }
                return "";
            } else {
                return "";
            }
        },
        _load() {
            const self = this

            if(!self.noMore){
                self.pageNo = self.pageNo + 1
                self._searchHouseNew()
            }            
        },

    },
    mounted() {
        const self = this

        self.cityCode = self._getUrlParam("cityCode")
        //点击弹框外任意区域，关闭弹框
        $(document).on('click', function (e) {
            var res = document.getElementById("resultTable");
            if (res) {
                if (!res.contains(e.target)) {
                    self.showResult = false;
                    self.isUp = false;
                    self.vheight = 30;
                }
            }
        });
        MapManager.getMapViewByIDAsy("mainMap").then((mapView) => {
            self.mapView = mapView;
            esriLoader
                .loadModules([
                    "esri/layers/MapImageLayer",
                    "esri/layers/TileLayer",
                    "esri/layers/FeatureLayer",
                    "esri/layers/GraphicsLayer",
                    "esri/renderers/ClassBreaksRenderer",
                    "esri/tasks/support/Query",
                    "esri/tasks/QueryTask",
                    "esri/geometry/Polygon",
                    "esri/geometry/Point",
                    "esri/Graphic",
                    "esri/core/watchUtils",
                ])
                .then(
                    ([
                        MapImageLayer,
                        TileLayer,
                        FeatureLayer,
                        GraphicsLayer,
                        ClassBreaksRenderer,
                        Query,
                        QueryTask,
                        Polygon,
                        Point,
                        Graphic,
                        watchUtils,
                    ]) => {
                        self.MapImageLayer = MapImageLayer
                        self.TileLayer = TileLayer
                        self.FeatureLayer = FeatureLayer;
                        self.GraphicsLayer = GraphicsLayer;
                        self.ClassBreaksRenderer = ClassBreaksRenderer;
                        self.Query = Query;
                        self.QueryTask = QueryTask;
                        self.Polygon = Polygon;
                        self.Point = Point;
                        self.Graphic = Graphic;
                        self.watchUtils = watchUtils;

                    }
                );
        });

    },
    beforeUpdate() {},
}
</script>

<style scoped>
.topsearch {
    position: fixed;
    left: 5vw;
    top: 3vh;
    width: 90vw;
    height: 5vh;
    z-index: 20;
}

.topsearch .top-result {
    width: 100%;
    height: 30px;
    background: #1296db;
    text-align: center;
}

.topsearch .search-result {
    /* color: white; */
    line-height: 30px;
    height: 30px;
    width: 100%;
    padding: 0 8px;
    cursor: pointer;
    border-radius: 4px;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
}

.loading {
    text-align: center;
}

.loading span {
    display: inline-block;
    width: 35px;
    margin: 0 auto;
    height: 35px;
    border: 3px solid #409eff;
    border-left: transparent;
    animation: zhuan 0.5s linear infinite;
    border-radius: 50%;
}

.topsearch ::v-deep .el-input-group__append,.el-input-group__prepend{
    background: #fff;
}
.topsearch ::v-deep .el-input-group__prepend{
    background: #fff;
}
.topsearch ::v-deep .el-button{
    width: 50px;
    padding: 0 0;
}

input{
    box-shadow:none !important;
}
</style>
